package com.zerdoor.shiro;

import com.zerdoor.dao.LoginDao;
import com.zerdoor.service.LoginService;
import com.zerdoor.util.ListUtil;
import org.apache.shiro.config.Ini;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by xiaoji on 2015/2/4.
 */
    public class ChainDefinitionSectionMetaSource implements FactoryBean<Ini.Section> {

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    /**
     * 默认premission字符串
     */
    public static final String PREMISSION_STRING="perms[\"{0}\"]";
    public static final String ROLES_STRING="roles[\"{0}\"]";

    private String filterChainDefinitions;

    @Override
    public Ini.Section getObject() throws Exception {
        //获取所有Resource
        List<Map<String, Object>> list = sqlSessionTemplate.selectList("LoginMapper.getResource");

        Ini ini = new Ini();
        //加载默认的url
        ini.load(filterChainDefinitions);
        Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        //循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,
        //里面的键就是链接URL,值就是存在什么条件才能访问该链接
        for (Map<String, Object> map : list) {
            //如果不为空值添加到section中
            if(map.get("url") != null && map.get("perms")!=null && map.get("roles")!=null) {
                String[] rolesArr = map.get("roles").toString().split(",");
                List<String> roles = new ArrayList<String>();
                for(int i=0;i<rolesArr.length;i++){
                    if(!list.contains(rolesArr[i])) {
                        roles.add(rolesArr[i]);
                    }
                }
                section.put(map.get("url").toString(),  MessageFormat.format(PREMISSION_STRING, ListUtil.listToString(roles,',')));
            }

        }

        return section;
    }

    /**
     * 通过filterChainDefinitions对默认的url过滤定义
     *
     * @param filterChainDefinitions 默认的url过滤定义
     */
    public void setFilterChainDefinitions(String filterChainDefinitions) {
        this.filterChainDefinitions = filterChainDefinitions;
    }


    @Override
    public Class<?> getObjectType() {
        return this.getClass();
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}
